<template>
  <el-dialog title="新增退货单" :close-on-click-modal="false" :visible.sync="visible" center fullscreen>
    <el-button class="miui-dialog-close-btn" @click="visible = false">关闭页面</el-button>
    <el-form :model="dataForm" ref="dataForm" label-width="120px">
      <el-row>
        <el-col :span="8">
          <el-form-item label="单据编号" prop="returnBillId">
            <el-input v-model="dataForm.returnBillId" readonly></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="入库类型">
            <el-input value="采购退货单" readonly></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="单据日期" prop="createTime">
            <el-input v-model="dataForm.createTime" readonly></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="制造商" prop="supplyName">
            <el-input v-model="dataForm.supplyName" readonly :disabled="this.disabledFlag">
              <el-button slot="append" @click="checkSupplyList" :disabled="this.disabledFlag">选择</el-button>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="发出仓位" prop="outStockId">
            <el-select v-model="dataForm.outStockId" placeholder="请选择" :disabled="this.disabledFlag">
              <el-option
                v-for="item in outStockOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="制单人" prop="createUsername">
            <el-input v-model="dataForm.createUsername" readonly></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="运单号" prop="transportId">
            <el-input v-model="dataForm.transportId"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="备注" prop="memo">
            <el-input type="textarea" :rows="2" placeholder="请输入内容" v-model="dataForm.memo"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-form :inline="true">
      <el-form-item>
        <el-radio-group v-model="calculate">
          <el-radio label="1">自动计算</el-radio>
          <el-radio label="2">手动计算</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <el-form :model="dataForm" ref="inputForm">
    <el-table
      :data="dataList"
      border
      v-loading="dataListLoading"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="code" label="商品代码"></el-table-column>
      <el-table-column prop="viewGoodsName" label="商品名称"></el-table-column>
      <el-table-column prop="spec" label="型号"></el-table-column>
      <el-table-column prop="number" label="数量"></el-table-column>
      <el-table-column prop="costPrice" label="单位成本">
            <template slot-scope="scope" >
              <el-form-item :prop="'goodsInfos.'+scope.$index+'.costPrice'" :rules="dataRule.costPrice">
                <el-input v-model="scope.row.costPrice" :disabled="calculate == 1"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="costPriceTotal" label="成本合计">
            <template slot-scope="scope" >
              <el-form-item :prop="'goodsInfos.'+scope.$index+'.costPriceTotal'" :rules="dataRule.costPriceTotal">
                <el-input v-model="scope.row.costPriceTotal" :disabled="calculate == 1"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="税率">
            <template slot-scope="scope" >
              <el-form-item :prop="'goodsInfos.'+scope.$index+'.taxRate'"  :rules="dataRule.taxRate">
                <el-input v-show="true" v-model="scope.row.taxRate" @change="changeTaxPrice(scope.row.taxRate)" placeholder="请输入税率"/>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="含税单价">
            <template slot-scope="scope">
              <el-form-item :prop="'goodsInfos.'+scope.$index+'.taxPrice'" :rules="dataRule.taxPrice">
                <el-input v-show="true" v-model="scope.row.taxPrice" @change="changeTaxPrice(scope.row.taxPrice)" placeholder="请输入含税单价"/>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="taxRateTotal" label="税额合计">
            <template slot-scope="scope" >
              <el-form-item :prop="'goodsInfos.'+scope.$index+'.taxRateTotal'" :rules="dataRule.taxRateTotal">
                <el-input v-model="scope.row.taxRateTotal" :disabled="calculate == 1"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="taxPriceTotal" label="价税合计">
            <template slot-scope="scope" >
              <el-form-item :prop="'goodsInfos.'+scope.$index+'.taxPriceTotal'" :rules="dataRule.taxPriceTotal">
                <el-input v-model="scope.row.taxPriceTotal" :disabled="calculate == 1"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
    </el-table>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">关闭</el-button>
      <el-button type="primary" @click="dataFormSubmit" :loading="ischeck" v-prevent-re-click>保存</el-button>
      <el-switch
        v-model="verify"
        active-text="保存并审核"
        inactive-value="1"
        active-value="2"
        style="margin-left: 15px;"
      ></el-switch>
    </span>
  </el-dialog>
</template>
<script>
import { filterParams } from "@/util/tools"
import { fetchStockList } from "@/api/eims/stock"
import { returnManagementById,editSettlementById } from "@/api/eims/return-management"
import { fetchCtgList } from "@/api/eims/goods"

export default {
  data() {
    var checkNumber = (rule, value, callback) => {//包含小数的数字
      let reg = /^[+-]?(0|([1-9]\d*))(\.\d+)?$/g;
      if (value === '') {
        callback()
      } else if (!reg.test(value)) {
        callback(new Error('请输入正确的价格'))
      } else {
        callback()
      }
    }
    return {
      ischeck: false,
      calculate: '1',
      nowTime: "",
      nowDate: "",
      visible: false,
      verify: false,
      dataForm: {
        id: 0,
        applyStatus: "0",
        goodsId: "",
        goodsName: "",
        supplyId: "",
        supplyName: "",
        memo: "",
        goodsInfos: [],
        deptId: ""
      },
      goodsOptions: [],
      dataList: [],
      outStockOptions: [],
      dataListLoading: false,
      supplySearchVisible: false,
      goodsListVisible: false,
      selectionList: [],
      disabledFlag: false,
      dataRule: {
        costPrice:  [
          {required: true, message: '请输入成本单价', trigger: 'blur'},
          {validator:checkNumber,trigger: "blur" }
        ],
        costPriceTotal:  [
          {required: true, message: '请输入成本总价', trigger: 'blur'},
          {validator:checkNumber,trigger: "blur" }
        ],
        taxRate: [
          {required: true, message: '请输入税率', trigger: 'blur'},
          {validator:checkNumber,trigger: "blur" }
        ],
        taxPrice: [
          {required: true,message: '请输入含税单价', trigger: 'blur'},
          {validator:checkNumber,trigger: "blur" }
        ],
        taxRateTotal: [
          {required: true, message: '请输入税额总价', trigger: 'blur'},
          {validator:checkNumber,trigger: "blur" }
        ],
        taxPriceTotal: [
          {required: true, message: '请输入含税总价', trigger: 'blur'},
          {validator:checkNumber,trigger: "blur" }
        ],
      },
    };
  },
  created() {
    this.timeFormate(new Date());
  },
  methods: {
    init(id) {
      this.disabledFlag = false
      this.dataForm.id = id || 0;
      if(this.dataForm.id != 0){
        this.disabledFlag = true
      }
      this.verify = "1"
      this.dataList = []
      this.getOutStockList();
      this.visible = true;
      if (this.dataForm.id) {
        this.dataListLoading = true
        returnManagementById(this.dataForm.id).then(response => {
          if(response.data.code == '0'){
            this.dataForm = response.data.data
            this.dataList = response.data.data.goodsInfos
            this.dataList.forEach(item => {
              item.costPriceTotal = (item.number * item.costPrice).toFixed(2);
              item.taxRateTotal = ((item.taxPrice - item.costPrice) * item.number).toFixed(2)
              item.taxPriceTotal = (item.number * item.taxPrice).toFixed(2)
            })
          }else{
            this.$message.error(response.data.msg)
          }
          this.dataListLoading = false
        })
      }
    },
    // 出仓选择
    stockNameChange($event) {
      this.outStockOptions.forEach(item => {
        if (item.value == $event) {
          this.dataForm.outStockName = item.label;
        }
      });
    },
    // 获取仓位列表
    getOutStockList() {
      fetchStockList().then(response => {
        if(response.data.code == '0'){
          this.outStockOptions = response.data.data.records
        }else{
          this.$message.error(response.data.msg)
        }
      })
    },
    // 商品类别改变时获取名字
    goodsSelectChange($event) {
      this.goodsOptions.forEach(item => {
        if (item.value == $event) {
          this.dataForm.goodsName = item.name;
        }
      });
    },
    checkSupplyList() {
      let data = { };
      this.supplySearchVisible = true;
      this.$nextTick(() => {
        this.$refs.supplySearch.init(data);
      });
    },
    // 选择制造商
    renewFormData(data) {
      this.dataForm.supplyId = data.id;
      this.dataForm.supplyName = data.name;
    },
    // 打开商品列表弹窗
    addGoodsBySingle() {
      // 判断是否选中制造商
      if (!this.dataForm.supplyId) {
        this.$message.warning("请选择制造商");
        return;
      }
      if (!this.dataForm.outStockId) {
        this.$message.warning("请选择发出仓位");
        return;
      }
      let params = {
        supplyId: this.dataForm.supplyId,
        supplyName: this.dataForm.supplyName,
        stockId: this.dataForm.outStockId
      };
      let data = { params: params, data: this.dataList };
      this.goodsListVisible = true;
      this.$nextTick(() => {
        this.$refs.sinleGoodsList.init(data);
      });
    },
    handleSelectionChange(val) {
      this.selectionList = val;
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs.inputForm.validate((valid1) => {
        if (!valid1) {
          this.$message.warning("输入的值格式有误")
          return
        }
        this.dataForm.verify = this.verify
        this.ischeck = true
        this.$refs["dataForm"].validate(valid => {
          if (valid) {
            editSettlementById(this.dataForm).then(response => {
              if(response.data.code == '0'){
                this.$message.success('修改成功')
                this.visible = false
                this.$emit('refreshDataList')
              }else{
                this.$message.error(response.data.msg)
              }
              this.ischeck = false
            }).catch(() => {
              this.ischeck = false
            })
          } else {
            this.ischeck = false
            return false
          }
        });
      });
    },
    //显示当前时间（年月日时分秒）
    timeFormate(timeStamp) {
      let year = new Date(timeStamp).getFullYear();
      let month =
        new Date(timeStamp).getMonth() + 1 < 10
          ? "0" + (new Date(timeStamp).getMonth() + 1)
          : new Date(timeStamp).getMonth() + 1;
      let date =
        new Date(timeStamp).getDate() < 10
          ? "0" + new Date(timeStamp).getDate()
          : new Date(timeStamp).getDate();
      let hh =
        new Date(timeStamp).getHours() < 10
          ? "0" + new Date(timeStamp).getHours()
          : new Date(timeStamp).getHours();
      let mm =
        new Date(timeStamp).getMinutes() < 10
          ? "0" + new Date(timeStamp).getMinutes()
          : new Date(timeStamp).getMinutes();
      let ss =
        new Date(timeStamp).getSeconds() < 10
          ? "0" + new Date(timeStamp).getSeconds()
          : new Date(timeStamp).getSeconds();
      this.nowTime =
        "POUT" +
        year +
        "" +
        month +
        "" +
        date +
        "" +
        hh +
        "" +
        mm +
        "" +
        ss +
        this.dataForm.deptId;
      this.nowDate = year + "-" + month + "-" + date;
    },
    //根据税率改变成本价格
    changeTaxRate(){
      if(this.calculate == 1){
        this.dataList.forEach(item => {
          item.costPrice = item.taxPrice / (1+item.taxRate/100)
          item.costPriceTotal = (item.number * item.costPrice).toFixed(2);
          item.taxRateTotal = ((item.taxPrice - item.costPrice) * item.number).toFixed(2)
        })
      }
    },
    changeTaxPrice(data,index){
      if(this.calculate == 1){
        this.dataList.forEach(item => {
          item.costPrice = item.taxPrice / (1+item.taxRate/100)
          item.costPriceTotal = (item.number * item.costPrice).toFixed(2);
          item.taxRateTotal = ((item.taxPrice - item.costPrice) * item.number).toFixed(2);
          item.taxPriceTotal = (item.number * item.taxPrice).toFixed(2)
        })
      }
    }
  }
}
</script>
